package com.cs.base.room;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.room.Room;


import java.util.List;


/**
 * @ClassName: MapRoomRepository
 * @Date: 2021/6/11
 * @Author: CS
 * @Description:  数据库操作
 */
public class MapRoomRepository {
    /*数据库名称*/
    public static final String DATABASE_NAME = "maproom_database";
    /*数据库实例*/
    private static MapRoomDao mapRoomDao;

    /**
     * 初始化数据库
     * @param context
     */
    public static void init(Context context){
        if(mapRoomDao == null){
            synchronized (MapRoomRepository.class) {
                if (mapRoomDao == null) {
                    MapRoomDatabase mapRoomDatabase = Room.databaseBuilder(context, MapRoomDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();
                    mapRoomDao = mapRoomDatabase.getDao();
                }
            }
        }
    }

    /**
     * 获取所有数据
     * @return
     */
    public static LiveData<List<MapRoom>> getAllMapRoomLive(){
        if(mapRoomDao == null){
            return null;
        }
        return mapRoomDao.getAllMapRoom();
    }


    /**获取用户数据
     * @param key
     * @return
     */
    public static MapRoom getMapRoomByKey(String key){
        if(mapRoomDao == null){
            return null;
        }
        return mapRoomDao.getMapRoomByKey(key);
    }

    /**获取用户数据
     * @param keys
     * @return
     */
    public static List<MapRoom> getMapRoomByKeys(String... keys){
        if(mapRoomDao == null){
            return null;
        }
        return mapRoomDao.getMapRoomByKeys(keys);
    }

    /**
     * 插入或者更新
     * @param cache
     */
    public static void insertOrUpdateMapRoom(MapRoom cache){
        if(mapRoomDao == null){
            return;
        }
        MapRoom mapRoom = mapRoomDao.getMapRoomByKey(cache.getKey());
        if(mapRoom == null){
            mapRoomDao.insertMapRoom(cache);
        }else {
            mapRoomDao.updateMapRoom(cache);
        }
    }

    /**
     * 删除
     * @param keys
     */
    public static void deleteMapRoomByKeys(String... keys){
        if(mapRoomDao == null){
            return;
        }
        mapRoomDao.deleteMapRoomByKeys(keys);
    }

    /**
     * 删除
     * @param caches
     */
    public static void deleteMapRoom(MapRoom... caches){
        if(mapRoomDao == null){
            return;
        }
        mapRoomDao.deleteMapRoom(caches);
    }

    /**
     * 清空数据库
     */
    public static void clearMapRoom(){
        if(mapRoomDao == null){
            return;
        }
        mapRoomDao.deleteAllMapRoom();
    }
}
